package emulator.hardware.nmos6502.commands;

import emulator.EmulatorException;
import emulator.hardware.HwByte;
import emulator.hardware.nmos6502.Command;
import emulator.hardware.nmos6502.CommandSet;
import emulator.hardware.nmos6502.Cpu6502;
import emulator.hardware.nmos6502.Flags6502;
import emulator.hardware.nmos6502.Operand;
import emulator.hardware.nmos6502.operands.*;

/** LSR (Logical Shift Right)
 *  
 *  Affects Flags: S Z C
 *  
 *  MODE           SYNTAX       HEX LEN TIM
 *  Accumulator   LSR A         $4A  1   2
 *  Zero Page     LSR $44       $46  2   5
 *  Zero Page,X   LSR $44,X     $56  2   6
 *  Absolute      LSR $4400     $4E  3   6
 *  Absolute,X    LSR $4400,X   $5E  3   7
 *  
 *  LSR shifts all bits right one position. 0 is shifted into bit 7 and the
 *  original bit 0 is shifted into the Carry. 
 */
public class LSR implements Command {

	@Override
	public void execute(Cpu6502 cpu, Operand operand) throws EmulatorException {
		HwByte value = operand.getByte();
		Flags6502 flags = cpu.getFlags();
		flags.setCarry(value.getBit(0));
		value.shift(-1);
		flags.setNZFromValue(value);
		operand.setByte(value);
		cpu.setFlags(flags);
	}

	@Override
	public String getName() {
		return "LSR";
	}

	@Override
	public void register(CommandSet cset) {
		cset.defineCommand(0x4A, this, new Accumulator());
		cset.defineCommand(0x46, this, new ZeroPage(), 4);
		cset.defineCommand(0x56, this, new ZeroPageX(), 4);
		cset.defineCommand(0x4E, this, new Absolute(), 4);
		cset.defineCommand(0x5E, this, new AbsoluteX(false), 5);
	}

}
